package kaaengine.loaders
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import kaaengine.core.SceneManager;
	import kaaengine.core.isometric.IsoStructure;
	import kaaengine.core.isometric.IsoWorld;
	import kaaengine.display.IView;
	[Event(name="MAP_LOADED", type="flash.events.Event")]
	public class MapLoader extends EventDispatcher
	{
		private static var DELIMITER:String = "\n";
		
		
		private var tab:Array;
		public var sm:SceneManager ;
		public var world:IsoWorld;
		public function MapLoader()
		{
			
		}
		public function loadMap( fileName:String, _sm:SceneManager):void {	
			sm = _sm;
					
			var request:URLRequest = new URLRequest(fileName);
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onMapFileLoaded);	
			loader.load(request);			
		}
		public function onMapFileLoaded(event:Event):void {	
			
			var loader:URLLoader = URLLoader(event.target);
			var str:String = loader.data as String;
			tab = str.split(DELIMITER); 
			var currentZone:String;
			for(var i:int=0;i< tab.length;i++){
				var line:String = tab[i];					
				if(line.substr(0,1)=="#") {
					currentZone = line;
				} else {	
					 if( currentZone == "#setup"){
						var ss:Array = line.split(";");
						world = sm.createIsoWorld(Number(ss[0]),Number(ss[1]),Number(ss[2]), Number(ss[3]), Number(ss[4]), Number(ss[5]), Number(ss[6])) as IsoWorld;
													
					} else  if( currentZone == "#tiles"){
						var ss:Array = line.split(";");
						for(var i:int = 0 ; i < world.tiles.length ; i++){
							if( Number(ss[i]) > -1 ) {
								var s:IsoStructure = sm.structuresRepository.getItemAt(Number(ss[i])) as IsoStructure;
								world.tiles[i].structures[0] = s;
							}				
						}
						;
						
					}
				}
			}
			dispatchEvent(new Event("MAP_LOADED"));	
		}
		

	}
}